<?php

namespace backend\controllers;

use backend\models\AdminUser;
use backend\models\Banner;
use backend\models\Check;
use backend\models\Goods;
use backend\models\Message;
use Yii;
use backend\models\LoginForm;
use backend\models\BannerSearch;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * BannerController implements the CRUD actions for Banner model.
 */
class ApiController extends BaseController
{



    public function actionLogin()
    {
        $model = new LoginForm();
        $time = 3600 * 3; //登录之后3小时免登陆
        if ( $model->load( Yii::$app->request->post() ) && $model->login( $time ) ) {
            $user_info = AdminUser::findOne( Yii::$app->user->identity->getId() );
            $user_info->scenario = 'logout';
            $user_info->last_time = date('Y-m-d H:i:s',time());
            $user_info->last_ip = Yii::$app->request->userIP;
            $user_info->save( FALSE );
            $this->redirect( [ 'index/main' ] );
        } else {
            return $this->render( 'login' , [
                'model' => $model ,
            ] );
        }
    }

    public function actionMains()
    {
        $banner         = Banner::find()->select('image,ctime,is_display')->orderBy(['ctime' => SORT_DESC])->where(['is_display'=>1])->orderBy('ctime desc')->limit(3)->asArray()->all();
        if(!$banner){
            return $this->error(['您还没上传轮播图']);
        }
        $project_num    = AdminUser::find()->where(['type'=>2])->count();
        $checking_num   = Check::find()->where(['status'=>1])->count();
        $checked_num    = Check::find()->where(['status'=>2])->count();
        $data = [
            'code'    => 200 ,
            'msg' => '' ,
            'banner'  => $banner ,
            'project_num'  => $project_num ,
            'checking_num' => $checking_num ,
            'checked_num'  => $checked_num ,
    ];
        echo json_encode($data);
    }

    //购买物资

    public function actionPurchase()
    {
        $postData = Yii::$app->request->post();
        if(empty($postData['name'] ) || empty($postData['model'] ) || empty($postData['unit']) || empty($postData['price']) || empty($postData['num']) || empty($postData['all_price']) || empty($postData['buy_time']) || empty($postData['image'])){
           $data = [
               'code' => 400 ,
               'message' => '参数不能为空' ,
           ];
        }else{
            $purchase['pid']       = Yii::$app->user->identity->getId();
            $purchase['name']      = $postData['name'];
            $purchase['model']     = $postData['model'];
            $purchase['unit']      = $postData['unit'];
            $purchase['num']       = $postData['num'];
            $purchase['price']     = $postData['price'];
            $purchase['all_price'] = $postData['all_price'];
            $purchase['buy_time']  = $postData['buy_time'];
            $purchase['image']     = $postData['image'];
            $purchase['provider']  = $postData['provider'];
            $purchase['status']    = 1;
            $ret  = Check::insert(false, $purchase);
            if($ret){
                $data = [
                    'code' => 200 ,
                    'msg' => '添加成功' ,
                ];
            }
        }
        echo json_encode($data);
    }
    // 报废列表
    public function actionScrapList()
    {
        $uerId  = Yii::$app->user->identity->getId();
        $list   = Goods::find()->select('id,name,model,buy_time,num')->where(['pid' => $uerId])->asArray()->all();
        if($list){
            $data = [
                'code' => 200,
                'msg'  => '查询成功',
                'data' => $list,
            ];
        }else{
            $data = [
                'code' => 400,
                'msg'  => '您的项目目前没有物资',
            ];
        }
        echo json_encode($data);

    }
    //报废申请
    public function actionScrapApply()
    {
        $postData = Yii::$app->request->post();
        if(empty($postData['id'] ) || empty($postData['num'] ) || empty($postData['reason'] )|| empty($postData['salvage'] )  || empty($postData['image'] )){
            $data = [
                'code' => 400 ,
                'msg' => '参数不能为空' ,
            ];
        }else{
            $postDatas = Goods::findOne(['id' => $postData['id']]);
            unset($postDatas['id']);
            $postDatas['num']        = $postData['num'];
            $postDatas['gid']        = $postData['id'];
            $postDatas['reason']     = $postData['reason'];
            $postDatas['salvage']    = $postData['salvage'];
            $postDatas['image']      = $postData['image'];
            $postDatas['status']     = 1;
            $postDatas['all_price']  = $postDatas['price']*$postData['num'];
            $ret = Check::insert(false, $postDatas);
            if($ret){
                $data = [
                    'code' => 200 ,
                    'msg' => '添加成功' ,
                ];
            }else{
                $data = [
                    'code' => 400 ,
                    'msg' => '添加失败' ,
                ];
            }
        }
        echo json_encode($data);
    }
    //我的 模块
    public function actionMine()
    {
        $datas['id'] = Yii::$app->user->identity->getId();
        $userInfo   = AdminUser::findOne(['id'=>$datas['id']]);
        $datas['username']     =  $userInfo['username'];
        $datas['project_name'] =  $userInfo['project_name'];
        $datas['leader']       =  $userInfo['leader'];
        $data =[
            'code' => 200,
            'msg'  => '查询成功',
            'data' => $datas,
        ];
        echo json_encode($data);
    }

    //我的项目
    public function actionMyProject()
    {
        $id = Yii::$app->user->identity->getId();
        $myGoods = Goods::find()->select('id,model,buy_time,num,use_num')->where(['pid' => $id])->asArray()->all();
        if($myGoods){
            $data =[
                'code' => 200,
                'msg'  => '查询成功',
                'data' => $myGoods,
            ];

        }else{
            $data =[
                'code' => 400,
                'msg'  => '您的项目目前没有物资',
            ];
        }
        echo json_encode($data);
    }

    //  修改使用数量
    public function actionEditUseNum()
    {
        $postData = Yii::$app->request->post();
        if(empty($postData['id']) || empty($postData['use_num'] )){
            $data = [
                'code' => 400 ,
                'msg' => '参数不能为空' ,
            ];
        }else{
            $ret = Goods::updateAll(['use_num' => $postData['use_num'] ], ['id' => $postData['id']]);
            if( $ret ){
                $data =[
                    'code' => 200,
                    'msg'  => '修改成功',
                ];
            }
        }
        echo json_encode($data);
    }

    //  消息列表
    public function actionMsgList()
    {
        $id = Yii::$app->user->identity->getId();
        $message = Message::find()->select('id,content,ctime,is_pass,pid')->where(['pid'=>$id])->asArray()->all();
        if($message){
            $data = [
                'code' => 200,
                'msg'  => '消息查询成功',
                ];
        }else{
            $data = [
                'code' => 400,
                'msg'  => '暂无消息数据',
            ];
        }
        echo json_encode($data);
    }


    //项目负责人审核通过
    public function actionMsgPass()
    {
        $postData = Yii::$app->request->post();//获取用户提交数据
        if(empty($postData['id']) || empty($postData['cid'])){
            $data = [
                'code' => 400 ,
                'msg' => '参数不能为空' ,
            ];
        }else{
            $tr = Yii::$app->db->beginTransaction();  //开启事务
            try {
                Check::updateAll(['status' => 1],['id' => $postData['cid']]);
                $check   = Check::find()->select('pid,num,name,unit')->where(['id' => $postData['cid']])->one();
                $project = AdminUser::find()->select('project_name')->where(['id' => $check['pid']])->one();
                $content = '您已通过'.$project['project_name'].'调用'.$check['num'].$check['unit'].$check['name'].'的申请';
                Message::updateAll([['content' => $content],['is_pass' => 2]],['cid' => $postData['cid']]);



                $tr->commit();
            }catch (Exception $e) {
                //回滚
                $tr->rollBack();
                echo  "rollback";
            }
            $data = [
                'code' => 200 ,
                'msg' => '您已同意对方的请求！' ,
            ];
        }
        echo json_encode($data);
    }

    //项目负责人审核拒绝
    public function actionMsgVeto()
    {
        $postData = Yii::$app->request->post();//获取用户提交数据
        if(empty($postData['id']) || empty($postData['cid'])){
            $data = [
                'code' => 400 ,
                'msg' => '参数不能为空' ,
            ];
        }else{
            $tr = Yii::$app->db->beginTransaction();  //开启事务
            try {
                Check::updateAll(['status' => 3],['id' => $postData['cid']]);
                $check   = Check::find()->select('pid,num,name,unit')->where(['id' => $postData['cid']])->one();
                $project = AdminUser::find()->select('project_name')->where(['id' => $check['pid']])->one();
                $content = '您已拒绝'.$project['project_name'].'调用'.$check['num'].$check['unit'].$check['name'].'的申请';
                Message::updateAll([['content' => $content],['is_pass' => 3]],['cid' => $postData['cid']]);
                $tr->commit();
            }catch (Exception $e) {
                //回滚
                $tr->rollBack();
                echo  "rollback";
            }
            $data = [
                'code' => 200 ,
                'msg' => '您已拒绝对方的请求！' ,
            ];
        }
        echo json_encode($data);
    }

   //物资调拨列表
    public function actionAllocateList()
    {
        $id    = Yii::$app->user->identity->getId();
        $name  = Yii::$app->request->post('name');
        $goods = Goods::find()->select('id,pid,name,model,buy_time,num')->where(['<>', 'id', $id])
            ->andFilterWhere(['like', 'name', $name])
            ->asArray()
            ->all();
        if($goods){
            $data = [
                'code' => 200,
                'msg'  => '列表查询成功',
            ];
        }else{
            $data = [
                'code' => 400,
                'msg'  => '暂无消息数据',
            ];
        }
        echo json_encode($data);
    }
    //物资调拨提交
    public function actionAllocateApply()
    {
        $postData = Yii::$app->request->post();
        $id       = Yii::$app->user->identity->getId();
        if(empty($postData['id']) || empty($postData['pid']) || empty($postData['num']) || empty($postData['use_time'])){
            $data = [
                'code' => 400 ,
                'msg' => '参数不能为空' ,
            ];
        }else{
            $tr = Yii::$app->db->beginTransaction();  //开启事务
            try {
                $goods = Goods::findOne(['id' => $postData['id']]);
                $check['pid']            = $id;
                $check['name']           = $goods['name'];
                $check['type']           = 2;
                $check['model']          = $goods['model'];
                $check['request_time']   = date('Y-m-d H:i:s',time());
                $check['request_num']    = $postData['num'];
                $check['recipient']      = $goods['recipient'];
                $check['provider']       = $goods['provider'];
                $check['unit']           = $goods['unit'];
                $check['image']          = $goods['image'];
                $check['status']         = 4;
                $check['buy_time']       = $goods['buy_time'];
                $check['price']          = $goods['price'];
                $check['all_price']      = $goods['price']*$postData['num'];
                $check['gid']            = $postData['id'];
                $check['bid']            = $goods['pid'] ;
                $check['use_time']       = $postData['use_time'];
                $cid   = Check::insert(false, $check);
                $bName = AdminUser::find()->select('project_name')->where(['id'=> $id])->one(); // 调用人
                $message['pid']     =  $goods['pid'];
                $message['content'] = '您是否同意'.$bName['project_name'].'调用您'.$postData['num'].$goods['unit'].$goods['name'].'?';
                $message['cid']     = $cid;
                $message['is_pass'] = 1;
                $message['ctime']   = date('Y-m-d H:i:s',time());
                Message::insert(false,$message);
                $tr->commit();
            }catch (Exception $e) {
                //回滚
                $tr->rollBack();
                echo  "rollback";
            }
            $data = [
                'code' => 200 ,
                'msg' => '调拨申请成功！' ,
            ];
        }
        echo json_encode($data);
    }



}